<?php
/**
 * Created by 张富琼 <zfuqiong@ifreegroup.com>.
 * User: kingzcheung
 * Date: 17-10-9
 * Time: 下午3:07
 */


namespace kingzcheung\migration\command;


use kingzcheung\migration\Lock;
use think\console\Command;

abstract class Sql extends Command {


    /**
     * @var array
     *
     * @author 张富琼 <zfuqiong@ifreegroup.com>
     */
    protected $sqls;

    /**
     * @return array
     */
    public function getSqls() {

        if (!$this->sqls) {
            $versions = [];

            $sqlFiles     = glob($this->getPath() . DS . '*.sql', GLOB_BRACE);
            $hasFileArray = array_column(Lock::all(), 'file');
            foreach ($sqlFiles as $sqlFile) {

                //查看run.lock是否已经存在曾经迁移过的sql文件,有的话需要过滤
                if (in_array(basename($sqlFile), $hasFileArray)) {
                    continue;
                }

                $version            = $this->getVersionFromFileName(basename($sqlFile));
                $versions[$version] = $sqlFile;
            }

            ksort($versions);
            $this->sqls = $versions;
        }

        return $this->sqls;
    }

    /**
     * 获取迁移SQL文件的目录
     *
     * @return string
     *
     * @author 张富琼 <zfuqiong@ifreegroup.com>
     */
    public function getPath() {
        return ROOT_PATH . 'migration/sql';
    }

    /**
     * 获取文件版本
     * @param $name
     * @return string
     *
     * @author 张富琼 <zfuqiong@ifreegroup.com>
     */
    private function getVersionFromFileName($name) {
        return strstr($name, '_', true);
    }

    /**
     * 获取SQL文件日期
     *
     * @param $name
     * @return bool|string
     *
     * @author 张富琼 <zfuqiong@ifreegroup.com>
     */
    private function getDateFromFromFileName($name) {
        return substr($name, 0, 8);
    }


}